package com.leejxx.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leejxx.admin.dao.AdUserDao;
import com.leejxx.admin.service.AdUserService;
import com.leejxx.model.common.dto.ResponseResult;
import com.leejxx.model.admin.dtos.UserDto;
import com.leejxx.model.common.enums.AppHttpCodeEnum;
import com.leejxx.model.admin.pojos.AdUser;
import com.leejxx.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author LeeJx
 * @ClassName AdUserServiceImpl
 * @Description TODO
 * @date 2021/2/19 18:04
 * @Version 1.0
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserDao, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(UserDto userDto) {
        if (StringUtils.isBlank(userDto.getName()) || StringUtils.isBlank(userDto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码不能为空");
        }
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getUsername, userDto.getName()));
        if (null != user) {
            String salt = user.getSalt();
            String password = userDto.getPassword();
            String pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (pwd.equals(user.getPassword())) {
                user.setLoginTime(new Date());
                updateById(user);

                Map<String, Object> map = new HashMap<>();
                map.put("token", AppJwtUtil.getToken(user.getId().longValue()));
                user.setPassword("");
                user.setSalt("");
                map.put("user", user);
                return ResponseResult.okResult(map);
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }
    }
}
